package com.clock;

import cn.hutool.extra.spring.SpringUtil;
import com.clock.config.SpringContextUtil;
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;

@Import(SpringUtil.class)

@EnableScheduling
@SpringBootApplication(scanBasePackages = "com.clock", exclude = {DataSourceAutoConfiguration.class})
public class AlarmApplication extends AbstractJavaFxApplicationSupport implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(AlarmApplication.class);

    public static void main(String[] args) {
        System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        launch(AlarmApplication.class, args);
        log.info("javafx启动成功");
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("系统正在启动中....");
        // 假装加载资源1s
        Thread.sleep(500);
    }

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(new ClassPathResource("layout/alarm.fxml").getURL());
        //loader.setControllerFactory(clazz -> SpringContextUtil.getContext().getBean(clazz));
        Parent root = loader.load();
        final Scene scene = new Scene(root);
        stage.setTitle("JavaFX 闹钟");
        stage.setScene(scene);
        stage.show();
        // ✅ 设置点击右上角 X 时退出程序
        stage.setOnCloseRequest(event -> {
            String applicationName = SpringUtil.getApplicationContext().getEnvironment().getProperty("spring.application.name");
            log.info("{}程序关闭中...", applicationName);
            // 可选：优雅关闭 Spring 应用上下文
            SpringApplication.exit(SpringUtil.getApplicationContext(), () -> 0);
            // 关闭 JavaFX 线程
            Platform.exit();
            // 最终强退 JVM（保险）
            System.exit(0);
        });
        //super.start(stage);
    }

    @Override
    public void stop() throws Exception {
        Platform.exit();
    }
}
